﻿using Com.JunCaiSoft.API.Common.AssistClass;
using Com.JunCaiSoft.API.WXWork.Dto;
using Com.JunCaiSoft.Common.Extension;
using Com.JunCaiSoft.SystemConfig.IDao;
using Com.JunCaiSoft.WXWork.Common;
using Com.JunCaiSoft.WXWork.RestFul;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting.Internal;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.WXWork.Controllers
{
    /// <summary>
    /// 企业微信通讯录
    /// </summary>
    [Route("api/WXWork/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class SendMessageController : Controller
    {
        /// <summary>
        /// 配置
        /// </summary>
        private IConfiguration Configuration { get; set; }
        /// <summary>
        /// 配置环境
        /// </summary>
        private readonly IWebHostEnvironment HostingEnvironment;
        /// <summary>
        /// BaseURL
        /// </summary>
        private readonly String BaseURL;
        /// <summary>
        /// AccessTokenURL
        /// </summary>
        private readonly String AccessTokenURL;
        /// <summary>
        /// App秘钥管理器
        /// </summary>
        private readonly IAppSecretManageDao AppSecret;
        /// <summary>
        /// 消息发送接口构造函数
        /// </summary>
        /// <param name="env"></param>
        public SendMessageController(IAppSecretManageDao appSecretManager, IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                               .SetBasePath(env.ContentRootPath)
                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                               .AddJsonFile("DataBaseExcute.json", optional: true, reloadOnChange: true);
            HostingEnvironment = env;
            Configuration = builder.Build();
            BaseURL = Configuration.GetSection("WXWork:BaseURL").Value;
            AccessTokenURL = BaseURL + Configuration.GetSection("WXWork:AccessTokenURL").Value;
            AppSecret = appSecretManager;
        }
        /// <summary>
        /// 发送文本卡片消息
        /// </summary>
        /// <param name="sendTextCardInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ActionResult> SendTextCardMessage(SendTextCardInfo sendTextCardInfo)
        {
            var a = (PartmentEnum)sendTextCardInfo.partment;

            var token = RedisCacheExtension.GetStringValue(a.ToString()+"AccessToken");

            if (String.IsNullOrEmpty(token))
            {
                
                String appkey = await AppSecret.AppKeyAsync(a.ToString());
                String corpsecret = await AppSecret.AppSecretManagerAsync(a.ToString());
                var accesstoken = WXWorkAccessToken.GetAccessToken(AccessTokenURL, appkey, corpsecret);
                RedisCacheExtension.SetStringValue(a.ToString() + "AccessToken", accesstoken.access_token, accesstoken.expires_in / 3600);
                token = accesstoken.access_token;
            }

            Int32 AgentID = await AppSecret.AgentIDAsync(a.ToString());

            sendTextCardInfo.access_token = token;

            sendTextCardInfo.body.agentid = AgentID;

            var url = BaseURL + "/message/send?access_token={0}";

            var sendResult = HttpExtension.HttpPost(String.Format(url,token), JsonConvert.SerializeObject(sendTextCardInfo.body));

            return await Task.Run(() => Content(JsonConvert.SerializeObject(sendResult)));
        }
    }
}
